package reconciliation

import (
	"net/http"
	"parking-lot-go-admin/config"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"strconv"

	"github.com/gin-gonic/gin"
)

func Import(c *gin.Context) {

	// 获取其他表单字段的值
	parkCode := c.PostForm("park_code")
	fileType := c.PostForm("type")

	//获取上传文件
	randomFileName, err := controller.GetUploadFile(c, "fileList")
	if err != nil {
		controller.Fail(c, err.Error())
		return
	}

	var reconciliationStruct model.ReconciliationStruct
	model.CreateModelData(
		model.Db,
		reconciliationStruct.TableName(),
		map[string]interface{}{
			"file_path": randomFileName,
			"type":      fileType,
			"park_code": parkCode,
			"status":    0,
		},
	)

	go func() {
		var reconciliationData model.ReconciliationStruct
		model.GetModelDataFirst(
			model.Db,
			reconciliationStruct.TableName(),
			&reconciliationData,
			model.QueryOptions{
				Conditions: map[string]interface{}{
					"status": 0,
				},
				OrderBy: "id asc",
			},
		)

		//记录id
		idStr := strconv.Itoa(reconciliationData.Id)

		//拼接url
		systemSection := config.Cfg.Section("SYSTEM")
		url := systemSection.Key("URL").String() + "reconciliation/import_handle?id=" + idStr

		//发送请求
		client := &http.Client{}
		req, err := http.NewRequest("GET", url, nil)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		// 发送请求
		resp, err := client.Do(req)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		defer resp.Body.Close()
	}()

	controller.Success(c, "请求成功")
}
